#include "Common.hpp"
#include "Log.hpp"
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <unistd.h>

using namespace LogModule;
struct sockaddr_in server;
int sockfd;
void ClientQuit(int signo)
{
    std::cout << "ClientQuit" << std::endl;
    (void)signo;
    const std::string quit = "QUIT";
    int n = ::sendto(sockfd, quit.c_str(), quit.size(), 0, CONV(&server), sizeof(server));
    
    exit(0);
}

void *Recver(void *args)
{
    while (true)
    {
        (void)args;
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        int n = ::recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, CONV(&temp), &len);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cerr << buffer << std::endl; 
        }
    }
}

int main(int argc,char* argv[])
{
    ENABLE_CONSOLE_LOG();
    if(argc != 3)
    {
        LOG(LogLevel::ERROR) << "Usage : " << argv[0] << " serverip serverport ";
        Die(1);
    }
    signal(2, ClientQuit);  
    //创建套接字
    sockfd = ::socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {
        LOG(LogLevel::ERROR) << "socket : " << strerror(errno);
        Die(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    //填充网络字段+bind
    //但客户端不需要bind,因为首次调用sendto之后OS自动会bind，并且客户端不需要一个固定的端口号
    memset(&server,0,sizeof(server));
    server.sin_addr.s_addr = ::inet_addr(serverip.c_str());
    server.sin_family = AF_INET;//套接字需要的协议簇
    server.sin_port = htons(serverport);


    pthread_t tid;
    pthread_create(&tid, nullptr, Recver, nullptr);

    // 1.2 启动的时候，给服务器推送消息即可
    const std::string online = " ... 来了哈!";
    int n = ::sendto(sockfd, online.c_str(), online.size(), 0, CONV(&server), sizeof(server));

    while(true)
    {
        std::cout << "please say# ";
        std::string message;
        std::cin >> message;
        ssize_t n = ::sendto(sockfd,message.c_str(),message.size(),0,CONV(&server),sizeof(server));
        (void) n;
    }

    return 0;
}